<template>
    <view class="overall">
       
        <view class="content">
            <view class="switch">
                <view>
                    <view>{{userInfo.nickname}}</view>
                    <view>就诊人ID：{{userInfo.id}}</view>
                </view>
                <view>
                    <view @click="exchanging">切换就诊人</view>
                </view>
            </view>
            <wd-status-tip v-if="logItem==null?true:false" image="content" tip="暂无内容" />

            <view class="manifest" v-for="(item ,index) in logItem" :key="index">
                <view>
                    <view>费用类型</view>
                    <view>门诊缴费</view>
                </view>
                <view>
                    <view>缴费金额</view>
                    <view style="color: #FFD897;">￥{{item.money}}</view>
                </view>
                <view>
                    <view>就诊时间</view>
                    <view>{{item.create_time}}</view>
                </view>
                <view>
                    <view>专科名称</view>
                    <view>{{item.depart_id}}</view>
                </view>
            </view>
            <button v-if="logItem==null?false:true" @click="showAmountPopup" class='buttom' block>我要缴费</button>
        </view>

        <!-- 自定义切换就诊人弹窗 -->
        <view class="popup-mask" v-if="show" @click="handleClose"></view>
        <view class="custom-popup" v-if="show">
            <view class="person">
                <view class="personTitle">
                    <view>切换就诊人</view>
                </view>
                <view class="personItem" v-for="(item, index) in cardInfo" :key="index" @click="substitution(item)">
                    <view>{{item.nickname}}</view>
                    <view>就诊ID号：{{item.id}}</view>
                </view>
                <view class="personBut">
                    <view @click="manage(1)">添加就诊人</view>
                    <view @click="manage(2)">管理就诊人</view>
                </view>
            </view>
        </view>

        <!-- 自定义输入金额弹窗（全屏） -->
        <view class="fullscreen-amount-popup" v-if="showAmount">
            <view class="amount-container">
                <view class="amount-header">
                    <view class="close-btn" @click="handleCloseAmount">×</view>
                    <view class="title">付款</view>
                </view>
                <view class="amount-input-wrapper">
                    <view class="amount-input" @click="showNumberKeyboard">
                        <view class="currency">¥</view>
                        <input 
                            type="digit" 
                            placeholder="请输入金额" 
                            v-model="paymentAmount" 
                            @confirm="confirmAmount"
                            maxlength="12"
                            disabled
                        />
                    </view>
                </view>
                <view class="amount-hint">
                    <view>最低金额0.01元</view>
                </view>
            </view>
            
            <!-- 底部操作按钮 -->
            <view class="amount-actions">
                <button class="cancel-btn" @click="handleCloseAmount">取消</button>
                <button class="confirm-btn" :disabled="!isValidAmount" @click="confirmAmount">确认付款</button>
            </view>
        </view>

        <!-- 自定义数字键盘弹窗 -->
        <view class="popup-mask" v-if="showNumberPad" @click="handleCloseNumberPad"></view>
        <view class="number-pad-popup" v-if="showNumberPad">
            <view class="number-keyboard">
                <view class="keyboard-row" v-for="(row, rowIndex) in keyboardLayout" :key="rowIndex">
                    <view class="keyboard-key" v-for="(key, keyIndex) in row" :key="keyIndex" 
                          @click="handleKeyPress(key)">
                        {{ key === 'delete' ? '删除' : key === 'empty' ? '' : key }}
                    </view>
                </view>
                <view class="keyboard-row">
                    <view class="keyboard-key" @click="handleCloseNumberPad">取消</view>
                    <view class="keyboard-key" @click="handleKeyPress('.')">.</view>
                    <view class="keyboard-key confirm-key" @click="handleCloseNumberPad">确认</view>
                </view>
            </view>
        </view>

        <!-- 自定义支付密码弹窗 -->
        <view class="popup-mask" v-if="showPassword" @click="handleClosePassword"></view>
        <view class="custom-cash-popup" v-if="showPassword">
            <view class="cash">
                <view class="passInput">
                    <view>请使用密码支付</view>
                    <view>{{paymentAmount}}元</view>
                    <view>余额（{{userInfo.money==undefined?'1200.56':userInfo.money}})</view>

                    <view class="password-input">
                        <view>请输入支付密码</view>
                        <view>
                            <input v-for="(item, index) in Array.from({ length: 6 })" :key="index" ref="inputs"
                                v-model="passwords[index]" @input="onInputs(index, $event)" maxlength="1"
                                type="password" disabled />
                        </view>
                    </view>
                </view>
                
                <!-- 自定义数字键盘 -->
                <view class="number-keyboard">
                    <view class="keyboard-row" v-for="(row, rowIndex) in keyboardLayout" :key="rowIndex">
                        <view class="keyboard-key" v-for="(key, keyIndex) in row" :key="keyIndex" 
                              @click="key === 'delete' ? onDelete() : onInput(key)">
                            {{ key === 'delete' ? '删除' : key === 'empty' ? '' : key }}
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script lang="ts" setup>
    import { ref, onMounted } from 'vue';
    import { card, payLogs, lists, recharge } from '/api/index.js';
    
    function handleClickLeft() {
        uni.navigateBack();
    }

    const userInfo = ref({});
    const cardInfo = ref([]);
    const logItem = ref([]);

    const show = ref<boolean>(false);
    const showAmount = ref<boolean>(false);
    const showPassword = ref<boolean>(false);
    const showNumberPad = ref<boolean>(false);
    const paymentAmount = ref('');
    const isValidAmount = ref(false);
    const passwords = ref(Array(6).fill(''));
    
    // 数字键盘布局
    const keyboardLayout = ref([
        ['1', '2', '3'],
        ['4', '5', '6'],
        ['7', '8', '9'],
        ['empty', '0', 'delete']
    ]);
    
    // 获取用户ID的方法
    const getUserId = async () => {
        try {
            const res = await uni.getStorage({ key: 'user' });
            return res.data?.data?.id;
        } catch (error) {
            console.error('获取用户ID失败:', error);
            uni.showToast({
                title: '获取用户信息失败，请重新登录',
                icon: 'none'
            });
            return null;
        }
    };

    async function fun() {
        try {
            const userId = await getUserId();
            if (!userId) return;
            
            // 获取就诊人信息
            const cardRes = await card({ user_id: userId });
            cardInfo.value = cardRes.data || [];
            
            // 查找当前选中的就诊人
            const activeCard = cardInfo.value.find(item => item.status === 1);
            if (activeCard) {
                userInfo.value = activeCard;
            }
            
            // 获取科室列表
            const deptRes = await lists({});
            const departments = deptRes.data?.[0]?.childrens || [];
            
            // 获取待缴费记录
            const logsRes = await payLogs({ user_id: userId });
            logItem.value = logsRes.data || [];
            
            // 格式化科室名称
            if (logItem.value.length) {
                logItem.value.forEach(item => {
                    if (item.depart_id === 1) {
                        item.depart_id = '内科';
                    } else {
                        const dept = departments.find(dept => dept.id === item.depart_id);
                        item.depart_id = dept?.name || item.depart_id;
                    }
                });
            }
        } catch (error) {
            console.error('加载数据失败:', error);
            uni.showToast({
                title: '网络错误，请稍后重试',
                icon: 'none'
            });
        }
    }

    onMounted(() => {
        fun();
    });

    function exchanging() {
        fun();
        show.value = true;
    }

    function handleClose() {
        show.value = false;
        passwords.value = Array(6).fill('');
    }
    
    function substitution(item) {
        userInfo.value = item;
        handleClose();
    }

    function showAmountPopup() {
        paymentAmount.value = '';
        isValidAmount.value = false;
        showAmount.value = true;
    }

    function handleCloseAmount() {
        showAmount.value = false;
        showNumberPad.value = false;
    }

    function handleClosePassword() {
        showPassword.value = false;
        passwords.value = Array(6).fill('');
    }

    function showNumberKeyboard() {
        showNumberPad.value = true;
    }

    function handleCloseNumberPad() {
        showNumberPad.value = false;
    }

    // 处理数字键盘按键
    function handleKeyPress(key) {
        if (key === 'delete') {
            onDeleteAmount();
        } else if (key !== 'empty') {
            onAmountInput(key);
        }
    }

    // 处理金额输入
    function onAmountInput(key) {
        // 防止非法输入
        if ((key >= '0' && key <= '9') || key === '.') {
            // 处理小数点
            if (key === '.') {
                // 如果当前没有小数点，才允许添加
                if (!paymentAmount.value.includes('.')) {
                    paymentAmount.value += '.';
                }
            } else {
                // 处理数字输入
                // 如果当前是0开头且后面不是小数点，则替换0
                if (paymentAmount.value === '0') {
                    paymentAmount.value = key;
                } else {
                    // 限制总长度不超过12位（包括小数点）
                    if (paymentAmount.value.length < 12) {
                        paymentAmount.value += key;
                    }
                }
            }
            
            // 验证金额有效性
            validateAmount();
        }
    }

    // 删除金额的最后一位
    function onDeleteAmount() {
        if (paymentAmount.value) {
            paymentAmount.value = paymentAmount.value.slice(0, -1);
            validateAmount();
        }
    }

    // 验证金额有效性
    function validateAmount() {
        // 确保金额至少为0.01元
        isValidAmount.value = 
            paymentAmount.value !== '' && 
            parseFloat(paymentAmount.value) >= 0.01 &&
            // 确保不会出现类似 "00.01" 的无效格式
            !(paymentAmount.value.startsWith('0') && paymentAmount.value.length > 1 && !paymentAmount.value.startsWith('0.'));
    }

    function confirmAmount() {
        if (!isValidAmount.value) {
            uni.showToast({
                title: '请输入有效的金额（最小0.01元）',
                icon: 'none'
            });
            return;
        }
        
        showAmount.value = false;
        showPassword.value = true;
    }

    function addToPhoneNumber(num) {
        // 找到第一个空位置填充数字
        for (let i = 0; i < passwords.value.length; i++) {
            if (!passwords.value[i]) {
                passwords.value[i] = num.toString();
                break;
            }
        }
        
        // 如果6位密码都已输入，调用支付接口
        if (passwords.value.every(p => p)) {
            afford();
        }
    }

    function clearPhoneNumber() {
        passwords.value = Array(6).fill('');
    }

    function onInputs(index, event) {
        const input = event.target;
        if (input.value) {
            // 自动跳转到下一个输入框
            if (index < 5) {
                input.blur();
                setTimeout(() => {
                    const nextInput = input.nextElementSibling;
                    if (nextInput) nextInput.focus();
                }, 0);
            }
        } else {
            // 如果删除内容，跳转到前一个输入框
            input.blur();
            setTimeout(() => {
                const prevInput = input.previousElementSibling;
                if (prevInput) prevInput.focus();
            }, 0);
        }
    }

    const onInput = (value) => {
        if (value !== 'delete' && value !== 'empty') {
            addToPhoneNumber(value);
        }
    }
    
    const onDelete = () => {
        // 从后往前找到第一个有值的位置并删除
        for (let i = passwords.value.length - 1; i >= 0; i--) {
            if (passwords.value[i]) {
                passwords.value[i] = '';
                break;
            }
        }
    }

    async function afford() {
        try {
            uni.showLoading({
                title: '支付处理中...',
                mask: true
            });
            
            const passwordStr = passwords.value.join('');
            console.log('支付密码:', passwordStr);
            
            // 调用充值/支付接口
            const res = await recharge({
                card: userInfo.value.card,
                money: parseFloat(paymentAmount.value),
                password: passwordStr // 实际项目中应使用加密传输
            });
            
            console.log('支付结果:', res);
            
            if (res.code === 1) {
                // 支付成功
                uni.showModal({
                    title: '支付成功',
                    content: `您已成功支付${paymentAmount.value}元`,
                    showCancel: false,
                    success: () => {
                        clearPhoneNumber();
                        handleClosePassword();
                        // 刷新数据
                        fun();
                        // 跳转到首页或缴费记录页
                        uni.switchTab({
                            url: '/pages/primary/primary'
                        });
                    }
                });
            } else {
                // 支付失败
                uni.showModal({
                    title: '支付失败',
                    content: res.message || '支付处理失败，请重试',
                    showCancel: false,
                    success: () => {
                        clearPhoneNumber();
                        handleClosePassword();
                        // 刷新数据
                        fun();
                    }
                });
            }
        } catch (error) {
            console.error('支付异常:', error);
            uni.showToast({
                title: '网络错误，请稍后重试',
                icon: 'none'
            });
        } finally {
            uni.hideLoading();
        }
    }

    function manage(index) {
        show.value = false;
        if (index === 1) {
            uni.navigateTo({
                url: '/pages/addition/addition',
            });
        } else if (index === 2) {
            uni.navigateTo({
                url: '/pages/patient/patient',
            });
        }
    }
</script>

<style scoped>
    /* 原有样式保持不变 */
    .overall {
        width: 100%;
        background-color: #F4F4F4;
        min-height: 100vh;
    }

    .title {
        width: 100%;
        height: 180rpx;
        color: white;
        display: flex;
        align-items: center;
    }

    .name {
        display: flex;
        align-items: center;
        font-weight: bold;
        font-size: 42rpx;
        width: 35%;
        justify-content: space-between;
        margin-top: 50rpx;
        margin-left: 3%;
    }

    .content {
        width: 100%;
    }

    .switch {
        width: 94%;
        height: 200rpx;
        padding: 0 3%;
        background-color: white;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20rpx;
    }

    .switch>view:first-child>view {
        padding-bottom: 18rpx;
    }

    .switch>view:first-child>view:first-child {
        font-weight: bold;
        font-size: 36rpx;
    }

    .switch>view:last-child>view {
        color: #40C5D3;
        border: 3rpx #40C5D3 solid;
        padding: 12rpx 20rpx;
        border-radius: 2000rpx;
        font-size: 30rpx;
    }

    .manifest {
        width: 100%;
        background-color: white;
        padding-top: 20rpx;
        margin-bottom: 20rpx;
    }

    .manifest>view {
        display: flex;
        width: 92%;
        height: 80rpx;
        align-items: center;
        margin-left: 4%;
        margin-right: 4%;
        justify-content: space-between;
    }

    .buttom {
        background-color: #3ECCB2;
        color: white;
        border-radius: 200rpx;
        position: fixed;
        bottom: 60rpx;
        width: 92%;
        margin: 0 4%;
    }

    .person {
        width: 100vw;
        padding-bottom: 2vh;
    }

    .personTitle {
        width: 100%;
        height: 100rpx;
        background-color: #00DACA;
        display: flex;
        justify-content: center;
        align-items: center;
        color: white;
        font-weight: bold;
        font-size: 32rpx;
    }

    .personItem {
        width: 96%;
        padding: 30rpx 0%;
        margin: 0 2%;
        height: 100rpx;
        border-bottom: #C7C7C7 1rpx solid;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    }

    .personBut {
        width: 100%;
        height: 100rpx;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .personBut>view {
        width: 50%;
        height: 100rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 28rpx;
        color: #00A8BB;
        border-bottom: #C7C7C7 1rpx solid;
    }

    .password-input input {
        width: 90rpx;
        height: 90rpx;
        text-align: center;
        font-size: 50rpx;
        border: 1rpx #BDBDBD solid;
    }

    .password-input {
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        color: #B6B6B6;
    }

    .password-input>view:last-child {
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        color: black;
        margin-top: 20rpx;
    }

    .passInput {
        width: 100%;
        min-height: 600rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-around;
        font-size: 32rpx;
    }

    .passInput>view:nth-child(2) {
        font-size: 60rpx;
        font-weight: bold;
    }

    /* 新增弹窗样式 */
    .popup-mask {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 999;
    }

    .custom-popup {
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        background-color: white;
        border-radius: 20rpx 20rpx 0 0;
        z-index: 1000;
        transform: translateY(0);
        transition: transform 0.3s ease;
    }

    .custom-cash-popup {
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        background-color: white;
        border-radius: 20rpx 20rpx 0 0;
        z-index: 1000;
        transform: translateY(0);
        transition: transform 0.3s ease;
    }

    /* 数字键盘样式 */
    .number-keyboard {
        width: 100%;
        background-color: #f5f5f5;
        padding: 20rpx 0;
    }

    .keyboard-row {
        display: flex;
        justify-content: space-around;
        margin-bottom: 20rpx;
    }

    .keyboard-key {
        width: 25%;
        height: 100rpx;
        background-color: white;
        border-radius: 10rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 40rpx;
        box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
    }

    .keyboard-key:active {
        background-color: #e0e0e0;
    }

    /* 全屏输入金额弹窗样式 */
    .fullscreen-amount-popup {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: white;
        z-index: 1000;
        display: flex;
        flex-direction: column;
    }

    .amount-container {
        flex: 1;
        padding: 40rpx 30rpx;
    }

    .amount-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 100rpx;
    }

    .close-btn {
        font-size: 40rpx;
        color: #999;
        width: 60rpx;
        height: 60rpx;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .title {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
    }

    .amount-input-wrapper {
        margin-top: 80rpx;
    }

    .amount-input {
        display: flex;
        align-items: center;
        padding: 20rpx 0;
        border-bottom: 1rpx solid #f5f5f5;
        cursor: pointer;
    }

    .currency {
        font-size: 60rpx;
        color: #333;
        margin-right: 20rpx;
    }

    .amount-input input {
        flex: 1;
        font-size: 45rpx;
        text-align: left;
        border: none;
        outline: none;
        background-color: transparent;
    }

    .amount-hint {
        margin-top: 30rpx;
        text-align: center;
        color: #999;
        font-size: 28rpx;
    }

    /* 底部操作按钮 */
    .amount-actions {
        display: flex;
        border-top: 1rpx solid #f5f5f5;
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
    }

    .amount-actions button {
        flex: 1;
        height: 100rpx;
        font-size: 36rpx;
        border: none;
        background-color: white;
    }

    .cancel-btn {
        color: #666;
    }

    .confirm-btn {
        color: #00DACA;
        font-weight: bold;
        border-left: 1rpx solid #f5f5f5;
    }

    .confirm-btn:disabled {
        color: #ccc;
    }

    /* 自定义数字键盘弹窗样式 */
    .number-pad-popup {
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        background-color: white;
        border-radius: 20rpx 20rpx 0 0;
        z-index: 1001;
        transform: translateY(0);
        transition: transform 0.3s ease;
    }

    .confirm-key {
        background-color: #00DACA;
        color: white;
    }
</style>